<template>
    <div v-show="visible">
        <div class="mem_tit" style="color: coral;">
            添加地址
        </div>
        <table border="0" class="add_tab" style="width:930px;" cellspacing="0" cellpadding="0">
            <tr>
                <td width="10%" align="right">配送地区</td>
                <td colspan="3" style="font-family:'宋体';">
                    省：
                    <!-- 省 -->
                    <select class="jj" name="province" v-model="p" @change="pChange">
                        <option value="">请选择...</option>
                        <option v-for="pr in provinceList" :key="pr.code" :value="pr.code">
                            {{ pr.name }}
                        </option>
                    </select>
                    市：
                    <!-- 市 -->
                    <select class="jj" name="city" v-model="c" @change="cChange">
                        <option value="">请选择...</option>
                        <option v-for="ci in cityList" :key="ci.code" :value="ci.code">
                            {{ ci.name }}
                        </option>
                    </select>
                    区：
                    <!-- 区 -->
                    <select class="jj" name="area" v-model="d">
                        <option value="">请选择...</option>
                        <option v-for="di in districtList" :key="di.code" :value="di.code">
                            {{ di.name }}
                        </option>
                    </select>
                    <span style="color: red;">{{ errMsg.addressErr }}</span>

                </td>
                <!-- <td>
                    是否默认
                </td> -->
                <!-- <td>
                    <input type="radio" name="isDefault" value="1">是
                    <input type="radio"  name="isDefault" value="0">否
                </td> -->
            </tr>
            <tr>
                <td align="right">收货人姓名</td>
                <td  style="font-family:'宋体'; width: 40%;">
                    <input type="text" class="add_ipt" v-model="addressInfo.userName" @blur="checUserName" />
                    <span style="color: red;">{{ errMsg.userNameErr }}</span>
                </td>
                <td align="right" style="width: 10%;">电子邮箱</td>
                <td style="font-family:'宋体';">
                    <input type="text" class="add_ipt" v-model="addressInfo.email" @blur="checEmail" />
                    <span style="color: red;">{{ errMsg.emailErr }}</span>
                </td>
            </tr>
            <tr>
                <td align="right">收货人手机</td>
                <td style="font-family:'宋体';">
                    <input type="text" class="add_ipt" v-model="addressInfo.mobile" @blur="checkMobile" />
                    <span style="color: red;">{{ errMsg.mobileErr }}</span>
                </td>
                <td align="right">备注</td>
                <td style="font-family:'宋体';"><input type="text" class="add_ipt" v-model="addressInfo.remark" /></td>
            </tr>
            <tr>
                <td align="right">详细地址</td>
                <td>
                    <input type="tex t" class="add_ipt" v-model="detail" @blur="checkDetail">
                    <span style="color: red;">{{ errMsg.detailErr }}</span>
                </td>
                <td align="right">是否设为默认</td>
                <td>
                    <input type="radio" name="default" :value="1" v-model="addressInfo.isDefault">是
                    <input type="radio" name="default" :value="0" v-model="addressInfo.isDefault">否
                </td>
            </tr>

        </table>
        <p align="right">
            <a href="#" @click.prevent="cancel">取消</a>&nbsp; &nbsp;
            <a href="#" class="add_b" @click.prevent="addAddress()">确认添加</a>
        </p>
    </div>
</template>

<script>
import areaData from '@/assets/area_format_object.json'

export default {
    name: 'AddAddressChoose',
    data() {
        return {
            p: '',   // 省 code
            c: '',   // 市 code
            d: '',   // 区 code
            provinceList: [],
            cityList: [],
            districtList: [],
            raw: {},          // 整个 json
            cityMap: {},      // { 省code: [市] }
            districtMap: {},  // { 市code: [区] }
            detail: '',
            addressInfo: {
                remark: '',
                address: '',
                email: '',
                mobile: '',
                userName: '',
                isDefault: 0
            },
            flag: {
                addressFlag: false,
                emailFlag: false,
                mobileFlag: false,
                userNameFlag: false,
                detailFlag: false
            },
            errMsg: {
                addressErr: '',
                emailErr: '',
                mobileErr: '',
                userNameErr: '',
                detailErr: ''
            },

        }
    },
    props: {
        visible: {
            type: Boolean,
            default: false
        }
    },
    mounted() {
        this.raw = areaData
        this.parseData()
        this.userId = window.sessionStorage.getItem('userId')
        this.p = this.provinceList[0]?.code || ''

    },
    methods: {
        // 把嵌套的省市区 JSON 拆成三张“映射表”
        parseData() {
            for (const pCode in this.raw) {
                const pObj = this.raw[pCode]
                this.provinceList.push({ code: pCode, name: pObj.n })
                this.$set(this.cityMap, pCode, [])
                for (const cCode in pObj.c) {
                    const cObj = pObj.c[cCode]
                    this.cityMap[pCode].push({ code: cCode, name: cObj.n })
                    this.$set(this.districtMap, cCode, [])
                    for (const dCode in cObj.c) {
                        this.districtMap[cCode].push({ code: dCode, name: cObj.c[dCode].n })
                    }
                }
            }
        },
        setAddress() {
            this.addressInfo.address = this.fullRegion;
        },

        // 省变化时，市和区都清空，并更新市列表
        pChange() {
            this.c = ''
            this.d = ''
            this.cityList = this.cityMap[this.p] || []
            if (this.cityList.length) {
                this.c = this.cityList[0].code
            }
        },
        // 市变化时，区清空，并更新区列表
        cChange() {
            this.d = ''
            this.districtList = this.districtMap[this.c] || []
            if (this.districtList.length) {
                this.d = this.districtList[0].code
            }
        },
        checkAddress() {
            if (this.p == '') {
                this.flag.addressFlag = false
                this.errMsg.addressErr = '地址不能为空！'
                return
            }
            this.flag.addressFlag = true
            this.errMsg.addressErr = ''
        },
        checkDetail() {
            if (this.detail == '') {
                this.flag.detailFlag = false
                this.errMsg.detailErr = '请输入详细地址！'
                return
            }
            this.flag.detailFlag = true
            this.errMsg.detailErr = ''
        },
        checEmail() {
            if (this.addressInfo.email == '') {
                this.flag.emailFlag = false
                this.errMsg.emailErr = "邮箱不能为空！"
                return
            }
            let partten = /^[^\s@]+@[^\s@]+.[^\s@]+$/
            if (!partten.test(this.addressInfo.email)) {
                this.flag.emailFlag = false
                this.errMsg.emailErr = "邮箱格式不正确！"
                return
            }
            this.flag.emailFlag = true
            this.errMsg.emailErr = ""
        },
        checkMobile() {
            if (this.addressInfo.mobile == '') {
                this.errMsg.mobileErr = "手机不能为空！"
                this.flag.mobileFlag = false
                return
            }
            let partten = /^1[3578]\d{9}$/
            if (!partten.test(this.addressInfo.mobile)) {
                this.errMsg.mobileErr = "手机格式不对！"
                this.flag.mobileFlag = false
                return
            }
            this.errMsg.mobileErr = ""
            this.flag.mobileFlag = true

        },
        checUserName() {
            if (this.addressInfo.userName == '') {
                this.errMsg.userNameErr = "请输入收货人姓名！"
                this.flag.userNameFlag = false
                return
            }
            this.errMsg.userNameErr = ""
            this.flag.userNameFlag = true
        },
        addAddress() {
            this.checkAddress()
            this.checUserName()
            this.checEmail()
            this.checkMobile()
            if (this.flag.mobileFlag && this.flag.emailFlag && this.flag.userNameFlag && this.flag.addressFlag) {
                this.$axios({
                    url: 'addAddress',
                    method: 'post',
                    data: {
                        userId: this.userId,
                        mobile: this.addressInfo.mobile,
                        email: this.addressInfo.email,
                        address: this.addressInfo.address+this.detail,
                        userName: this.addressInfo.userName,
                        remark: this.addressInfo.remark,
                        isDefault:this.addressInfo.isDefault
                    },
                    headers: {
                        'content-type': 'application/json'
                    }
                }).then(rs => {
                    if (rs.data.code == 5200 || rs.data.code == '5200') {
                        alert('添加成功！')
                        this.cancel()
                        this.$emit('added')
                    } else {
                        alert('添加失败！')
                    }
                })
            }
        },
        
        cancel() {
            this.$emit('update:visible', false);   // 触发“.sync”语法
        }
    },
    // 获取存储地址广东省 广州市 天河区
    computed: {
        fullRegion() {
            const pr = this.provinceList.find(v => v.code === this.p)
            const ci = this.cityList.find(v => v.code === this.c)
            const di = this.districtList.find(v => v.code === this.d)
            return [pr?.name + '省', ci?.name + '市', di?.name + '区'].filter(Boolean).join('')
        },
        addShow() {
            return this.visible
        }

    },
    watch: {
        p() { this.pChange(); this.setAddress(); },
        c() { this.cChange(); this.setAddress(); },
        d() { this.setAddress(); }
    }
}
</script>
<style scoped>
    td>span{
        font-size: 10px;
    }
</style>